package com.example.shop.service.impl;

import com.example.shop.domain.Order;
import com.example.shop.enums.ResultExceptionEnum;
import com.example.shop.exception.ShopException;
import com.example.shop.service.OrderService;
import com.example.shop.service.PayService;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.RefundRequest;
import com.lly835.bestpay.model.RefundResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class PayServiceImpl implements PayService {

    @Autowired
    private BestPayServiceImpl bestPayService;

    @Autowired
    private OrderService orderService;

    @Override
    public PayResponse create(Order order) {
        PayRequest payRequest = new PayRequest();
        payRequest.setOpenid(order.getOpenid());
        payRequest.setOrderAmount(order.getAmount().intValue());
        payRequest.setOrderName("微信点餐订单");
        payRequest.setOrderId(order.getId());
        payRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
        return bestPayService.pay(payRequest);
    }



    @Override
    public PayResponse notify(String notifyData) {
        //1.验证签名
        //2.支付状态

        PayResponse payResponse = bestPayService.asyncNotify(notifyData);

        //3.支付金额判断
        //查询订单是否存在
        Order order = orderService.findOne(payResponse.getOrderId());
        log.error("订单查不存在!");
        //金额是否一致
        if (order == null) {
            throw new ShopException(ResultExceptionEnum.ORDER_NOT_EXIST);
        }

        //判断金额是否一致
        if (!(order.getAmount().intValue()-(payResponse.getOrderAmount())==0)) {
            log.error("异步通知,订单金额不一致");

            System.out.println(payResponse.getOrderId());
            throw new ShopException(ResultExceptionEnum.AMOUNT_NOTTURE);
        }

        orderService.paid(order.getId());

        return payResponse;

    }

    //退款
    @Override
    public RefundResponse refund(Order order) {
        RefundRequest refundRequest = new RefundRequest();
        refundRequest.setOrderId(order.getId());
        refundRequest.setOrderAmount(order.getAmount().intValue());
        refundRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);

        RefundResponse refundResponse = bestPayService.refund(refundRequest);

        return refundResponse;
    }
}
